//
//  NZTaxiAppDelegate.m
//  NZTaxi
//
//  Created by Allan Vergara on 7/09/10.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "NZTaxiAppDelegate.h"
#import "Region.h"
#import "Street.h"


@implementation NZTaxiAppDelegate

@synthesize window;
@synthesize tabBarController;
@synthesize orderNavController;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    // Override point for customization after application launch.

    // Add the tab bar controller's view to the window and display.
    [window addSubview:tabBarController.view];
    [window makeKeyAndVisible];
	
	//NSString *defaultStorePath = @"NZTaxi.sqlite";
	NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"NZTaxi" ofType:@"sqlite"];
	NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"NZTaxi.sqlite"];
	
	NSError *error;
	if (![[NSFileManager defaultManager] fileExistsAtPath:storePath]) 
	{
		if ([[NSFileManager defaultManager] copyItemAtPath:defaultStorePath toPath:storePath error:&error])
			NSLog(@"Copied starting data to %@", storePath);
		else 
			NSLog(@"Error copying default DB to %@ (%@)", storePath, error);
	}

	
	//[self GetIt];
	//[self DoIt];
	

    return YES;
}

-(void)DoIt {
	//Region *region = (Region *)[NSEntityDescription insertNewObjectForEntityForName:@"Region" 
///															 inManagedObjectContext:self.managedObjectContext];
	
	NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Region" inManagedObjectContext:self.managedObjectContext];
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Region == %@", @"Christchurch"];
	[fetch setPredicate:predicate];
	[fetch setEntity:entity];
	NSArray *testArray = [self.managedObjectContext executeFetchRequest:fetch error:nil];
	
	Region *region = (Region *)[testArray objectAtIndex:0];
															
		
	Street *street = (Street *)[NSEntityDescription insertNewObjectForEntityForName:@"Street" 
															 inManagedObjectContext:self.managedObjectContext];
	//street.Region = @"Timaru";
	street.Street = @"Kirk Road";
	street.Suburb = @"Templeton";
	[region addStreetObject:street];
	[self saveContext];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}


#pragma mark -
#pragma mark UITabBarControllerDelegate methods

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
}
*/

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
}
*/

#pragma mark -
#pragma mark Core Data stack

-(void)GetIt {
	//return;
	////Region *region = (Region *)[NSEntityDescription insertNewObjectForEntityForName:@"Region" 
	//														 inManagedObjectContext:self.managedObjectContext];
//	region.Region = @"Christchurch";
	
//	[self saveContext];
	
	NSString *defaultStorePath = @"foo.sqlite";
	NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"NZTaxi.sqlite"];
	
	
	if ([[NSFileManager defaultManager] copyItemAtPath:storePath toPath:defaultStorePath error:nil])
		NSLog(@"Copied starting data to %@", storePath);
	
	return;
	
	//NSDictionary *subs = [NSDictionary dictionaryWithObject:@"T" forKey:@"CHAR"];
	//NSFetchRequest *fetch = [self.managedObjectModel fetchRequestFromTemplateWithName:@"GetRegions" substitutionVariables:subs];
	NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
	NSEntityDescription *entity = [NSEntityDescription entityForName:@"Region" inManagedObjectContext:self.managedObjectContext];
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Region CONTAINS[cd] %@", @""];
	[fetch setPredicate:predicate];
	[fetch setEntity:entity];
	NSArray *testArray = [self.managedObjectContext executeFetchRequest:fetch error:nil];
	

	
	for (int i = 0; i < [testArray count]; i++) {
		Region *region = (Region *)[testArray objectAtIndex:i];
		NSLog(@"%@", region.Region);
	}
}

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext {
    
    if (managedObjectContext_ != nil) {
        return managedObjectContext_;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext_ = [[NSManagedObjectContext alloc] init];
        [managedObjectContext_ setPersistentStoreCoordinator:coordinator];
    }
    return managedObjectContext_;
}


/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel {
    
    if (managedObjectModel_ != nil) {
        return managedObjectModel_;
    }
    NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"NZTaxi" ofType:@"momd"];
    NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
    managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    
    return managedObjectModel_;
}


/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator 
{
    @synchronized (self)
    {
        if (persistentStoreCoordinator_ != nil)
            return persistentStoreCoordinator_;
        
        NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"NZTaxi.sqlite"];
		NSURL *storeURL = [NSURL fileURLWithPath:storePath];
        NSError *error;
        
        persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
        
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
        
        if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL 
															 options:options error:&error]) 
        {
            
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }    
        
        return persistentStoreCoordinator_;
    }    
}

- (void)saveContext {
    
    NSError *error = nil;
    if (managedObjectContext_ != nil) {
        if ([managedObjectContext_ hasChanges] && ![managedObjectContext_ save:&error]) {
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}


#pragma mark -
#pragma mark Application's Documents directory

/**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc {
	
	// remove core data objects
	[managedObjectContext_ release];
    [managedObjectModel_ release];
    [persistentStoreCoordinator_ release];
	
	[orderNavController release];
    [tabBarController release];
    [window release];
    [super dealloc];
}

@end

